<template>
	<div class="zco-im-mobile-footer-container" id="mobile-footer">
		<div class="zco-im-footer-contianer">
			<div class="zco-im-message-input">
				<div class="zco-im-emoji-icon">
					<img :src="showEmoji ? keyboard : emojiIcon" alt="" srcset="" width="24px" class="zco-im-send-emoji" @click="selectEmoji($event)" />
				</div>
				<!-- 可编辑文本 -->
				<div @click="textAreaHandler" id="textarea-editer-container">
					<EditerTextArea
						:text="html"
						:onCreated="onCreated"
						:onChange="onChange"
						:onDestroyed="onDestroyed"
						:onMaxLength="onMaxLength"
						:onFocus="onFocus"
						:onBlur="onBlur"
						:customAlert="customAlert"
						:customPaste="customPaste"
						:editorConfig="editorConfig"
					/>
				</div>

				<div class="zco-im-right-tool">
					<button class="zco-im-mobile-send-btn" :style="html && html.length > 0 ? 'background: #252B48;border-radius: 4px;' : ''" :disabled="!html" @click="sendMessageText">{{
						$t('send')
					}}</button>
					<img src="../../assets/img/more.png" alt="" srcset="" width="24px" @click="setShowTools($event)" v-if="!hideMoreButton" />
				</div>
			</div>
			<div class="emoji-wrapper" v-if="showEmoji" id="zco-emoji-wrapper">
				<Emoji @addEmoji="addEmoji"></Emoji>
			</div>

			<div class="zco-im-send-file-image-container" v-if="showTools && !showEmoji">
				<div class="zco-im-mobile-send-photograph-box" v-if="!hideVideoButton">
					<img src="../../assets/img/mobile-photo.png" alt="" srcset="" width="44px" @click="clickSendVideo" />
					<p class="zco-im-mobile-send-ptoto-text">{{ $t('camera-shooting') }}</p>
					<input style="display: none" type="file" name="file" id="videofile" accept="video/*" capture="environment" @change="sendVideo($event)" multiple />
				</div>
				<div class="zco-im-mobile-send-photograph-box" v-if="!hidePhotoButton">
					<img src="../../assets/img/mobile-photo.png" alt="" srcset="" width="44px" @click="clickSendPhoto" />
					<p class="zco-im-mobile-send-ptoto-text">{{ $t('take-photo') }}</p>
					<input style="display: none" type="file" name="file" id="phonefile" accept="image/*" capture="environment" @change="sendPhoto($event)" multiple />
				</div>
				<div class="zco-im-mobile-send-img-box" v-if="!hideImageButton">
					<img src="../../assets/img/mobile-send-img.png" alt="" srcset="" width="44px" @click="clickSendImage" />
					<p class="zco-im-mobile-send-img-text">{{ $t('picture') }}</p>
					<input style="display: none" type="file" name="file" id="imgfile" value="" accept="image/gif,image/jpg,image/jpeg,image/png" @change="sendImage($event)" />
				</div>
				<div class="zco-im-mobile-send-file-box" v-if="!hideFileButton">
					<img src="../../assets/img/mobile-send-file.png" alt="" srcset="" width="44px" @click="clickSendFile" />
					<p class="zco-im-mobile-send-file-text">{{ $t('file') }}</p>
					<input style="display: none" type="file" name="docfile" id="docfile" value="" @change="sendFile($event)" />
				</div>

				<div v-if="['im'].includes(type)" class="zco-im-mobile-send-file-box" :class="members > 2 ? 'disable' : ''">
					<img :src="members > 2 ? audioDisableImage : audioImage" alt="" width="44px" @click="clickAudioCall" />
					<p class="zco-im-mobile-send-file-text" :class="members > 2 ? 'disable' : ''">{{ $t('voice-call') }}</p>
				</div>
				<div v-if="['im'].includes(type)" class="zco-im-mobile-send-file-box" :class="members > 2 ? 'disable' : ''">
					<img :src="members > 2 ? videoDisableImage : videoImage" alt="" width="44px" @click="clickVideoCall" />
					<p class="zco-im-mobile-send-file-text" :class="members > 2 ? 'disable' : ''">{{ $t('video-call') }}</p>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import { sendMessageToRecord } from '../../utils/message';
import zcoIMEvent from '@/store/event';
import ZcoIM from '../../index';
import Emoji from '../Emoji';

import EditerTextArea from './EditerTextArea.vue';
import { updateMessageBoxHeight4Mobile } from '../../utils/util';
// import { getSelection, updateCaret } from '../../utils/contentEditable';
const emojiIcon = require('../../assets/img/sendEmoji.png');
const keyboard = require('../../assets/img/keyboard.png');

export default {
	data() {
		return {
			showTools: false,
			message: false,
			contentHieght: 0,
			hideVideoButton: false, // 隐藏摄像按钮
			hidePhotoButton: false, // 隐藏拍照按钮
			hideImageButton: false, // 隐藏图片按钮
			hideFileButton: false, // 隐藏文件按钮
			hideMoreButton: ZcoIM.hideMoreButton, // 隐藏更多按钮
			lastEditRange: null,
			emojiIcon: emojiIcon,
			keyboard: keyboard,
			showEmoji: false,
			type: '', // im | video | audio
			members: 0, // 在线人数
			audioImage: require('../../assets/img/audio-call.png'),
			audioDisableImage: require('../../assets/img/audio-disable-mobile.png'),
			videoImage: require('../../assets/img/video-call.png'),
			videoDisableImage: require('../../assets/img/video-disable-mobile.png'),
			isRequesting: false, // 是否在请求中

			// 编辑器属性
			editor: null,
			html: '',
			toolbarConfig: {},
			editorConfig: { placeholder: this.$t('enter-content') },
			mode: 'simple', // or 'simple'
			lastSelection: {
				anchor: { path: [0, 0], offset: 0 },
				focus: { path: [0, 0], offset: 0 }
			},
			offset: 0,
			originalHeight: window.innerHeight
		};
	},
	components: {
		Emoji,
		EditerTextArea
	},
	computed: {},

	watch: {
		showTools: {
			handler(newValue, oldValue) {
				if (newValue === oldValue) return;
				this.$nextTick(() => {
					updateMessageBoxHeight4Mobile(ZcoIM.type);
					this.$nextTick(() => {
						updateMessageBoxHeight4Mobile(ZcoIM.type);
					});
				});
			}
		},
		showEmoji: {
			handler(newValue, oldValue) {
				if (newValue === oldValue) return;
				this.$nextTick(() => {
					updateMessageBoxHeight4Mobile(ZcoIM.type);
					this.$nextTick(() => {
						updateMessageBoxHeight4Mobile(ZcoIM.type);
					});
				});
				// notify the parent component
				zcoIMEvent.emitEmojiShowHide(newValue);
			}
		}
	},
	mounted() {
		this.imgIcon = emojiIcon;
		// 粘贴
		// this.initPaste();
		document.body.addEventListener('click', e => {
			if (!e.target.className) {
				return;
			}
			if (this.showTools) {
				this.showTools = !this.showTools;
			}
			if (this.showEmoji) {
				this.showEmoji = !this.showEmoji;
			}
		});

		updateMessageBoxHeight4Mobile(ZcoIM.type);

		document.querySelector('.w-e-text-container').addEventListener('click', () => {
			// this.editor.focus();
		});

		document.getElementById('textarea-editer-container').addEventListener('keyup', e => {
			if (e.keyCode === 13) {
				this.getScrollHeight();
			}
			if (e.keyCode === 8) {
				this.getScrollHeight();
			}
		});

		// const textContainer = document.getElementById('widget-message-text');
		// textContainer.addEventListener('DOMNodeInserted', e => {
		// 	console.log('zco-DOMNodeInserted', e, new Date());
		// 	this.message = true;
		// });
		zcoIMEvent.onHangUp(data => {
			console.log('zco-im-hangup', data, new Date());
			this.message = false;
			if (this.editor) {
				this.editor.clear();
			}
		});

		zcoIMEvent.onUpdatMobileTitle(data => {
			const { type, members } = data || {};
			this.type = type;
			this.members = members;
		});
	},
	methods: {
		/**
		 * 添加emoji到input
		 */
		addEmoji(emoji) {
			const editor = this.editor; // 获取 editor 实例
			if (editor == null) return;
			// editor.disable();

			editor.select(this.lastSelection);
			editor.insertText(emoji);
		},
		/**
		 * 图片消息发送
		 * @params file
		 */
		async handleImgUpload(imageFile) {
			const isJpgOrPng = imageFile.type === 'image/jpeg' || imageFile.type === 'image/png' || imageFile.type === 'image/jpg' || imageFile.type === 'image/gif';
			if (!isJpgOrPng) {
				return this.$message.error(this.$t('image-not-support'));
			}
			// const isLt1M = imageFile.size / 1024 / 1024 < 0.5;
			if (imageFile.size > ZcoIM.maxUploadFileSize) {
				return this.$message.error(this.$t('file-limit-500-kbs'));
			}
			let image = new Image();
			let url = window.URL || window.webkitURL;
			image.src = url.createObjectURL(imageFile);
			image.onload = () => {
				let imageSize = this.getImageSize({ width: image.width, height: image.height });
				console.log(imageSize);
			};
		},

		/**
		 * 计算图片的比例
		 */
		getImageSize(data) {
			let { width, height } = data;
			if (width > 335 || height > 335) {
				if (width > height) {
					height = 335 * (height / width);
					width = 335;
				} else {
					width = 335 * (width / height);
					height = 335;
				}
			}
			return {
				width,
				height
			};
		},
		/**
		 * 监听图片粘贴事件
		 */
		initPaste() {
			document.addEventListener('paste', event => {
				let items = event.clipboardData && event.clipboardData.items;
				// let url = window.URL || window.webkitURL;
				let file = null;
				if (items && items.length) {
					// 检索剪切板items
					for (let i = 0; i < items.length; i++) {
						if (items[i].type.indexOf('image') !== -1) {
							file = items[i].getAsFile();
							break;
						}
					}
				}
				if (file) {
					console.log(file);
					// upload file
					this.handleImgUpload(file);
				}
			});
		},
		setShowTools(event) {
			event.preventDefault();
			event.stopPropagation();
			this.showTools = !this.showTools;
			this.hidePhotoButton = ZcoIM.hidePhotoButton;
			this.hideVideoButton = ZcoIM.hideVideoButton;
			this.hideImageButton = ZcoIM.hideImageButton;
			this.hideFileButton = ZcoIM.hideFileButton;
			if (this.showEmoji) {
				this.showEmoji = false;
			}
			if (this.showTools) {
				const self = this;
				setTimeout(() => {
					self.scrollToBottom();
				}, 300);
			}
		},
		inputFocus() {
			if (this.showTools) {
				this.showTools = false;
			}
		},
		clickSendImage() {
			document.getElementById('imgfile').click();
		},
		clickSendFile() {
			document.getElementById('docfile').click();
		},
		inputText(e) {
			if (e.target.innerHTML) {
				this.message = true;
			} else {
				this.message = false;
			}
		},
		selectEmoji(event) {
			event.preventDefault();
			event.stopPropagation();
			this.showEmoji = !this.showEmoji;
		},
		// 发纯文本
		sendMessageText() {
			const messageContent = this.editor.getText();
			if (messageContent == '') {
				return;
			}
			console.warn('zco-sendMessageText: ', messageContent, new Date());

			const data = sendMessageToRecord('text', messageContent, ZcoIM.client, 'in-progress');
			ZcoIM.setChatMessage(data);
			zcoIMEvent.emitTextMessage(data);
			this.html = '';
			this.editor.clear();
			this.lastSelection = {
				anchor: { path: [0, 0], offset: 0 },
				focus: { path: [0, 0], offset: 0 }
			};
			updateMessageBoxHeight4Mobile(ZcoIM.type);
			this.getScrollHeight();
			document.body.removeEventListener('touchmove', this.stop, {
				passive: false
			});
			this.message = false;
		},
		sendImage(event) {
			const files = document.getElementById('imgfile').files;
			if (!files || files.length <= 0) {
				event.target.value = null;
				this.emitUploadEnd();
				return;
			}
			const file = files[0];
			let imgTest = ['png', 'jpg', 'jpeg', 'gif'];
			let index = file.name.lastIndexOf('.');
			let ext = file.name.substr(index + 1).toLowerCase();
			if (imgTest.indexOf(ext) === -1) {
				this.$zcoMessage({
					type: 'error',
					message: `图片仅支持png,jpg,jpeg,gif格式,请重新选择`,
					duration: 3
				});
				event.target.value = null;
				this.emitUploadEnd();
				return;
			}
			if (file.size > ZcoIM.maxUploadFileSize) {
				this.$zcoMessage({
					type: 'error',
					message: this.$t('file-limit-500-kbs'),
					duration: 3
				});
				event.target.value = null;
				return;
			}
			let URL = window.URL || window.webkitURL;
			let imgURL = URL.createObjectURL(file);
			console.log('zco-im-web-sendImg-imgURL:', imgURL, new Date());
			let msgData = {};
			msgData.url = imgURL;
			msgData.type = 'pic';
			msgData.name = file.name;
			msgData.file = file;
			const data = sendMessageToRecord('link', msgData, ZcoIM.client, 'in-progress');
			ZcoIM.setChatMessage(data);
			zcoIMEvent.emitResourceMessage(data);
			event.target.value = null;
			this.emitUploadEnd();
		},
		// 发文件， 举例： pdf,doc,text
		sendFile(event) {
			const files = document.getElementById('docfile').files;
			if (!files || files.length <= 0) {
				event.target.value = null;
				this.emitUploadEnd();
				return;
			}
			let file = files[0];
			if (file.size > ZcoIM.maxUploadFileSize) {
				this.$zcoMessage({
					type: 'error',
					message: this.$t('file-limit-500-kbs'),
					duration: 3
				});
				event.target.value = null;
				this.emitUploadEnd();
				return;
			}
			let URL = window.URL || window.webkitURL;
			let fileURL = URL.createObjectURL(file);
			console.log('zco-im-sendFile-fileURL:', fileURL, new Date());
			let msgData = {};
			msgData.url = fileURL;
			msgData.type = 'doc';
			msgData.name = file.name;
			msgData.file = file;
			msgData.suffix = file.name.substring(file.name.lastIndexOf('.') + 1);
			const data = sendMessageToRecord('link', msgData, ZcoIM.client, 'in-progress');
			ZcoIM.setChatMessage(data);
			zcoIMEvent.emitResourceMessage(data);
			event.target.value = null;
			this.emitUploadEnd();
		},

		getScrollHeight() {
			// 让滚动条始终在最底部
			this.$nextTick(() => {
				const container = document.getElementById('textarea-editer-container');
				const scrollHeight = container.scrollHeight;
				let scrollTop = container.scrollTop;
				const height = container.offsetHeight;
				console.log('zco-getScrollHeight:', scrollHeight, scrollTop, height, new Date());
				container.scrollTop = scrollHeight;
				updateMessageBoxHeight4Mobile(ZcoIM.type);
			});
		},
		clickSendPhoto() {
			document.getElementById('phonefile').click();
		},
		sendPhoto(event) {
			console.log('zco-im-mobile-sendPhoto: ', event, new Date().toISOString());
			const files = document.getElementById('phonefile').files;
			if (!files || files.length <= 0) {
				event.target.value = null;
				this.emitUploadEnd();
				return;
			}
			const file = files[0];
			let URL = window.URL || window.webkitURL;
			let imgURL = URL.createObjectURL(file);
			console.log('zco-im-mobile-sendPhoto-imgURL:', imgURL, new Date().toISOString());
			let msgData = {};
			msgData.url = imgURL;
			msgData.type = 'pic';
			msgData.name = file.name;
			msgData.file = file;
			const data = sendMessageToRecord('link', msgData, ZcoIM.client, 'in-progress');
			ZcoIM.setChatMessage(data);
			zcoIMEvent.emitResourceMessage(data);
			event.target.value = null;
			this.emitUploadEnd();
		},
		clickSendVideo() {
			document.getElementById('videofile').click();
		},
		sendVideo(event) {
			const files = document.getElementById('videofile').files;
			if (!files || files.length <= 0) {
				event.target.value = null;
				this.emitUploadEnd();
				return;
			}
			const file = files[0];
			if (file.size > ZcoIM.maxUploadFileSize) {
				this.$zcoMessage({
					type: 'error',
					message: `发送的文件大小超过限制`,
					duration: 3
				});
				event.target.value = null;
				this.emitUploadEnd();
				return;
			}
			let URL = window.URL || window.webkitURL;
			let videoURL = URL.createObjectURL(file);
			let msgData = {};
			msgData.url = videoURL;
			msgData.type = 'video';
			msgData.name = file.name;
			msgData.file = file;
			msgData.suffix = file.name.substring(file.name.lastIndexOf('.') + 1);
			msgData.suffix = msgData.suffix.toLowerCase();
			const data = sendMessageToRecord('link', msgData, ZcoIM.client, 'in-progress');
			ZcoIM.setChatMessage(data);
			zcoIMEvent.emitResourceMessage(data);
			event.target.value = null;
			this.emitUploadEnd();
		},
		emitUploadEnd() {
			this.$nextTick(() => {
				zcoIMEvent.emitUploadEnd();
			});
		},
		// 点击语音通话按钮
		clickAudioCall() {
			if (this.members > 2) {
				this.$zcoMessage({
					type: 'warning',
					message: `${this.$t('multi-party-not-support-upgrading')}`,
					duration: 3
				});
				return;
			}
			if (this.isRequesting) return;
			this.isRequesting = true;
			zcoIMEvent.requestAudioCall();
			const self = this;
			setTimeout(() => {
				self.isRequesting = false;
			}, 1000);
		},
		// 点击视频通话按钮
		clickVideoCall() {
			if (this.members > 2) {
				this.$zcoMessage({
					type: 'warning',
					message: `${this.$t('multi-party-not-support-upgrading')}`,
					duration: 3
				});
				return;
			}
			if (this.isRequesting) return;
			this.isRequesting = true;
			zcoIMEvent.requestVideoCall();
			const self = this;
			setTimeout(() => {
				self.isRequesting = false;
			}, 1000);
		},
		hideTools() {
			if (this.showTools) {
				this.showTools = false;
			}
		},
		scrollToBottom() {
			const div = document.getElementById('chat-message');
			if (div) {
				div.scrollTo({
					top: div.scrollHeight
				});
			}
		},

		// 编辑器方法
		onCreated(editor) {
			this.editor = Object.seal(editor);
			console.log('onCreated', editor);
		},
		onChange(editor) {
			if (editor.selection) {
				this.lastSelection = editor.selection;
			} else {
				// this.offset = this.editor.getText().length;
			}
			this.html = this.editor.getText();

			console.log('onChange', editor.children, editor.selection, this.offset);
		},
		onDestroyed(editor) {
			console.log('onDestroyed', editor);
		},
		onMaxLength(editor) {
			console.log('onMaxLength', editor);
		},
		onFocus(editor) {
			console.log('onFocus', editor);

			document.body.addEventListener('touchmove', this.stop, {
				passive: false
			}); // p
		},
		textAreaHandler() {
			if (this.showTools) {
				this.showTools = false;
			}

			// 计算IOS软键盘偏移
			// const footer = document.getElementById('mobile-footer');
			// const textarea = document.getElementById('textarea-editer-container');
			if (this.showEmoji) {
				this.showEmoji = false;
				// footer.style.marginBottom = textarea.clientHeight / 2 + 'px';
				setTimeout(() => {
					this.scrollIntoView();
				}, 1000);
			} else {
				// footer.style.marginBottom = '0px';
			}
		},
		onBlur(editor) {
			console.log('onBlur', editor);
			document.body.removeEventListener('touchmove', this.stop, {
				passive: false
			});
		},
		customAlert(info, type) {
			window.alert(`customAlert in Vue demo\n${type}:\n${info}`);
		},
		customPaste(editor, event, callback) {
			console.log('ClipboardEvent 粘贴事件对象', event);
			// const html = event.clipboardData.getData('text/html') // 获取粘贴的 html
			// const text = event.clipboardData.getData('text/plain') // 获取粘贴的纯文本
			// const rtf = event.clipboardData.getData('text/rtf') // 获取 rtf 数据（如从 word wsp 复制粘贴）

			// 自定义插入内容

			// 返回 false ，阻止默认粘贴行为
			event.preventDefault();
			callback(false); // 返回值（注意，vue 事件的返回值，不能用 return
		},
		stop(e) {
			e.preventDefault(); // 阻挠默许的处理方式(阻挠下拉滑动的作用)
		},
		scrollIntoView() {
			if (window.scrollY <= 0) {
				return;
			}
			const footer = document.getElementById('mobile-footer');
			const rect = footer.getBoundingClientRect();
			console.log('平滑滚动', window.scrollY, rect.bottom, window.visualViewport.height, window.innerHeight);
			if (window.visualViewport.height < rect.bottom) {
				window.scrollTo({
					top: window.scrollY + rect.bottom - window.visualViewport.height,
					behavior: 'smooth'
				});
			}
		}
	},
	beforeDestroy() {
		const editor = this.editor;
		if (editor == null) return;
		editor.destroy(); // 组件销毁时，及时销毁编辑器
	}
};
</script>

<style>
#mobile-footer .w-e-text-placeholder {
	pointer-events: none;
}
</style>

<style scoped>
.zco-im-tools {
	position: absolute;
	bottom: -1px;
	display: flex;
	align-items: center;
	width: 100%;
	justify-content: end;
	height: 50px;
	background-color: #ffffff;
	border-bottom: 1px solid #bebebe;
}
.zco-im-right-tool {
	position: absolute;
	right: 10px;
	bottom: 17px;
	display: flex;
	align-items: center;
}
.zco-im-emoji-icon {
	position: absolute;
	left: 10px;
	bottom: 17px;
}
.zco-im-emoji-wrapper {
	padding: 10px 8px;
	background-color: #f8f8f8;
}

.zco-im-footer-contianer {
	width: 100%;
	height: 100%;
}
.zco-im-message-input {
	box-sizing: content-box !important;
	position: relative;
	min-height: 50px;
	padding: 10px;
	align-items: center;
	display: flex;
}
.zco-im-mobile-footer-container {
	width: 100%;
	position: absolute;
	bottom: 0;
	background: #ffffff;
	box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, 0.1);
	overflow: hidden;
}
.zco-im-widget-message-text {
	width: calc(100vw - 190px);
	min-height: 20px;
	line-height: 20px;
	margin-left: 40px;
	padding: 8px 10px;
	border: 1px solid #eee;
	background: #f2f2f2;
	max-height: 170px;
	border-radius: 6px;
	outline: none;
	overflow: auto;
}

.zco-im-mobile-send-btn {
	width: fit-content;
	min-width: 54px;
	white-space: nowrap;
	height: 34px;
	background: #e2e2e2;
	border-radius: 4px;
	border: 0;
	color: #ffffff;
	font-size: 13px;
	margin-right: 12px;
	box-sizing: border-box;
}
.zco-im-send-emoji {
}
.zco-im-emoji-content {
	overflow-x: hidden;
}
.zco-im-widget-message-text[contenteditable]:empty:before {
	content: attr(placeholder);
	width: 100%;
	font-size: 14px;
	display: block;
	height: 20px;
	font-weight: 400;
	color: #b9b9b9;
}
/* .widget-message-text[contenteditable]:focus {
	content: none;
	border: 0;
} */
.zco-im-widget-message-text {
	font-size: 14px;
}
.zco-im-mobile-send-img-text,
.zco-im-mobile-send-ptoto-text {
	font-size: 12px;
	font-weight: 400;
	color: #666666;
	text-align: center;
}
.zco-im-mobile-send-file-text {
	font-size: 12px;
	font-weight: 400;
	color: #666666;
	text-align: center;
	white-space: nowrap;
}
.zco-im-send-file-image-container {
	display: flex;
	padding: 6px 16px 14px 16px;
	overflow-x: auto;
	box-sizing: border-box;
}
.zco-im-mobile-send-img-box {
	padding-right: 20px;
}
.zco-im-mobile-send-photograph-box {
	padding-right: 20px;
}
.zco-im-mobile-send-file-box {
	padding-right: 20px;
	box-sizing: border-box;
}
.disable {
	color: #cccccc;
}
</style>
